package com.lamda.worker.timer;

import com.lamda.worker.WorkerHolder;
import com.lamda.worker.constraints.Configuration;
import org.apache.log4j.Logger;
import org.izao.IZaoClient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {

    public static final Logger LOGGER = Logger.getLogger(ScheduledTasks.class);

    @Autowired
    private WorkerHolder workerHolder;

    /**
     * 每隔5分钟向服务器报告一次vps的运行情况
     */
    @Scheduled(cron = "0 */1 *  * * * ")
    public void reportVpsStatus(){
        if (this.workerHolder.getiZaoClient().getStatus() != IZaoClient.Status.Connected) {
            return;
        }
        this.workerHolder.reportVpsStatus();
    }

    /**
     * 重连
     */
    //每1分钟执行一次
//    @Scheduled(cron = "0 */1 *  * * * ")
    @Scheduled(fixedRate = 500 * 1,initialDelay = 1000*10)
    public void reconnect() {
        //如果iZaoClient处于非disconnected状态 则不做任何处理
        if (workerHolder.getiZaoClient().getStatus() != IZaoClient.Status.DisConneted) {
            return;
        }
        LOGGER.info("reconnect...");
        //iZao处于断开状态，开始重连
        this.workerHolder.getiZaoClient().setStatus(IZaoClient.Status.Connecting);
        //开始连接服务器
        boolean isOK = this.workerHolder.getiZaoClient().connect();
        LOGGER.info("reconnect:" + isOK);

    }

    /**
     * 发送心跳信息(每30m秒进行一次)
     */
    @Scheduled(fixedRate = 500 * 1,initialDelay = 1000*10)
    public void sendHeartbeat() {
        if (this.workerHolder.getiZaoClient().getStatus() != IZaoClient.Status.Connected) {
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", "1");
        this.workerHolder.getiZaoClient().inform(Configuration.WorkerRoute.HEARTBEAT, jsonObject);
    }

}